import React, { Component } from 'react';
import {
    StyleSheet,
    Text,
    View,
    TouchableNativeFeedback,
    ListView,
    Dimensions,
} from 'react-native';

const SCREEN        = Dimensions.get('window');
const SCREEN_HEIGHT = Dimensions.get('window').height;
const SCREEN_WIDTH  = Dimensions.get('window').width;
const CELL_WIDTH    = SCREEN_WIDTH / 3;
const CELL_HEIGHT   = SCREEN_WIDTH / 6;

/** 按键视图 */
class Key extends Component {
    text;

    constructor(props) {
        super(props);
    }

    render() {
        this.text = this.props.text;
        return (
            <TouchableNativeFeedback
                onPress={() => this.props.onPress(this.text)}
                onLongPress={() => this.props.onLongPress(this.text)}
                background={TouchableNativeFeedback.SelectableBackground()}>
                <View style={styles.keyView}>
                    <Text style={styles.keyText} >{this.text}</Text>
                </View>
            </TouchableNativeFeedback>
        );
    }
}

/** 按键视图 */
export default class KeyBoardView extends Component {
    mText = ['1','2','3','4','5','6','7','8','9','X','0','←'];
    constructor(props) {
        super(props);
        const datas = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
        this.state = {
            mDatas : datas.cloneWithRows(this.mText),
            mCallBack: props.callBack,
        }
    }

    render() {
        return (
            <View ref="root" style={styles.flexTop}>
                <ListView
                    ref="list"
                    dataSource={this.state.mDatas}
                    renderRow={this._renderRow.bind(this)}
                    enableEmptySections = {true}
                    contentContainerStyle={styles.listViewStyle}
                />
            </View>
        );
    }

    _renderRow(rowData, sectionID, rowID){
        return <Key
            text={rowData}
            onPress={(text) => this._onPress(text)}
            onLongPress={(text) => this._onLongPress(text)}
        />;
    }

    _onPress(text){
        this.state.mCallBack(text, false);
    }

    _onLongPress(text){
        this.state.mCallBack(text, true);
    }

    getHeight(){
        let line = Math.ceil(this.mText.length / 3.0);
        return line * CELL_HEIGHT;
    }
}

const styles = StyleSheet.create({
    flexTop:{
        backgroundColor: '#000000',
    },
    listViewStyle:{
        flexDirection:'row',    // 主轴方向
        flexWrap:'wrap',        // 一行显示不下,换一行
        alignItems:'center',    // 侧轴方向, 必须设置,否则换行不起作用
    },
    keyView:{
        justifyContent: 'center',
        alignItems: 'center',
        width: CELL_WIDTH,
        height: CELL_HEIGHT,
        backgroundColor: '#FFFFFF',
        borderWidth: 0.3,
        borderColor: '#000000',
    },
    keyText:{
        fontSize: 30,
        fontWeight:'bold',
    },
});
